﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Collections;
using System.Data.SqlClient;
using System.Collections.Generic;

namespace PeekService
{
    public sealed class DBHelper
    {
        //获取数据库连接字符串，其属于静态变量且只读，项目中所有文档可以直接使用，但不能修改
        public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.ConnectionStrings["AlertsAndTaskEntities"].ToString();

        // 哈希表用来存储缓存的参数信息，哈希表可以存储任意类型的参数。
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

        #region ExecuteNonQuery
        /// <summary>
        ///执行一个不需要返回值的SqlCommand命令，通过指定专用的连接字符串。
        /// 使用参数数组形式提供参数列表 
        /// </summary>
        /// <remarks>
        /// 使用示例：
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">一个有效的数据库连接字符串</param>
        /// <param name="commandType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {

            SqlCommand cmd = new SqlCommand();

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                //通过PrePareCommand方法将参数逐个加入到SqlCommand的参数集合中
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                int val = cmd.ExecuteNonQuery();

                //清空SqlCommand中的参数列表
                cmd.Parameters.Clear();
                return val;
            }
        }
        /// <summary>
        /// 执行一个不需要返回值的SqlCommand命令,默认使用SQL语句
        /// </summary>
        /// <param name="cmdText"> T-SQL语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        public static int ExecuteNonQuery(string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecuteNonQuery(ConnectionStringLocalTransaction, CommandType.Text, cmdText, commandParameters);
        }
        /// <summary>
        ///  执行一个不需要返回值的SqlCommand命令,不带任何参数
        /// </summary>
        /// <param name="cmdText">T-SQL语句</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        public static int ExecuteNonQuery(string cmdText)
        {
            return ExecuteNonQuery(ConnectionStringLocalTransaction, CommandType.Text, cmdText, null);
        }
        /// <summary>
        ///执行一条不返回结果的SqlCommand，通过一个已经存在的数据库连接 
        /// 使用参数数组提供参数
        /// </summary>
        /// <remarks>
        /// 使用示例：  
        ///  int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">一个现有的数据库连接</param>
        /// <param name="commandType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {

            SqlCommand cmd = new SqlCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// 执行一条不返回结果的SqlCommand，通过一个已经存在的数据库事物处理 
        /// 使用参数数组提供参数
        /// </summary>
        /// <remarks>
        /// 使用示例： 
        ///  int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="trans">一个存在的 sql 事物处理</param>
        /// <param name="commandType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        #endregion


        #region 执行多条SQL语句，实现数据库事务。

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        public static void ExecuteSqlTran(Hashtable SQLStringList)
        {
            using (SqlConnection conn = new SqlConnection(ConnectionStringLocalTransaction))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    SqlCommand cmd = new SqlCommand();
                    try
                    {
                        //循环
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {
                            string cmdText = myDE.Key.ToString();
                            SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
                            PrepareCommand(cmd, conn, trans,CommandType.Text, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                    }
                }
            }
        }



        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>        
        public static void ExecuteSqlTran(string connectionString, List<string> SQLStringList)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                SqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    for (int n = 0; n < SQLStringList.Count; n++)
                    {
                        string strsql = SQLStringList[n].ToString();
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                }
                catch (System.Data.SqlClient.SqlException E)
                {
                    tx.Rollback();
                    throw new Exception(E.Message);
                }
            }
        }
        public static void ExecuteSqlTran(List<string> SQLStringList)
        {
            ExecuteSqlTran(ConnectionStringLocalTransaction, SQLStringList);
        }

        #endregion


        #region ExecuteReader(执行sql语句，返回DataReader)
        /// <summary>
        /// 执行一条返回结果集的SqlCommand命令，通过专用的连接字符串。
        /// 使用参数数组提供参数
        /// </summary>
        /// <remarks>
        /// 使用示例：  
        ///  SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">一个有效的数据库连接字符串</param>
        /// <param name="commandType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个包含结果的SqlDataReader</returns>
        public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);

            // 在这里使用try/catch处理是因为如果方法出现异常，则SqlDataReader就不存在，
            //CommandBehavior.CloseConnection的语句就不会执行，触发的异常由catch捕获。
            //关闭数据库连接，并通过throw再次引发捕捉到的异常。
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch
            {
                conn.Close();
                throw;
            }
        }
        /// <summary>
        /// 执行一条返回结果集的SqlCommand命令，默认使用SQL语句
        /// </summary>
        /// <param name="cmdText">T-SQL语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个包含结果的SqlDataReader</returns>
        public static SqlDataReader ExecuteReader(string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecuteReader(ConnectionStringLocalTransaction, CommandType.Text, cmdText, commandParameters);
        }


        /// <summary>
        /// 执行一条返回结果集的SqlCommand命令,不使用任何参数
        /// </summary>
        /// <param name="cmdText">T-SQL语句</param>
        /// <returns>返回一个包含结果的SqlDataReader</returns>
        public static SqlDataReader ExecuteReader(string cmdText)
        {
            return ExecuteReader(ConnectionStringLocalTransaction, CommandType.Text, cmdText, null);
        }

        /// <summary>
        /// 执行一条返回结果集的SqlCommand命令,不使用任何参数(分页)
        /// </summary>
        /// <param name="cmdText">T-SQL语句</param>
        /// <param name="pageIndex">页索引</param>
        /// <param name="pageSize">页数据大小</param>
        /// <param name="RecordCount">输出参数，输出总记录条数</param>
        /// <returns>返回一个包含结果的SqlDataReader</returns>
        public static SqlDataReader ExecuteReader(string cmdText, int pageIndex, int pageSize, out int RecordCount)
        {
            RecordCount = 0;
            if (!string.IsNullOrEmpty(cmdText))
            {
                if (cmdText.ToLower().IndexOf("order") > -1)
                {
                    string strCmdText1 = cmdText.Substring(0, cmdText.ToLower().IndexOf("order"));
                    string strCmdText2 = cmdText.Substring(cmdText.ToLower().IndexOf("order"));
                    string countSQL = "SELECT COUNT(*) FROM (" + strCmdText1 + ") as T";
                    object obj = DBHelper.ExecuteScalar(countSQL);
                    if (obj != null && obj != DBNull.Value)
                    {
                        RecordCount = int.Parse(obj.ToString());
                    }
                    int CurrentPageIndex = pageIndex - 1;
                    int PageSizes = pageSize;
                    int rowStart = (CurrentPageIndex * PageSizes) + 1;//当前页的起始序号
                    int rowEnd = (CurrentPageIndex + 1) * PageSizes;//当前页的结束序号
                    string querySQL = @"declare @ID_Num int;
                                   SET @ID_Num = @ID_Num +1
                                   SELECT * FROM (SELECT t1.*,ROW_NUMBER() OVER (ORDER BY @ID_Num DESC)  sn 
                                   FROM (" + strCmdText1.ToUpper().Replace("SELECT","SELECT TOP "+ pageIndex*pageSize) +  strCmdText2+") t1) t2 " +
                                       " WHERE t2.sn BETWEEN " + rowStart.ToString() + " AND " + rowEnd.ToString() ;

                    return ExecuteReader(ConnectionStringLocalTransaction, CommandType.Text, querySQL, null);

                }
                else
                {
                    string countSQL = "SELECT COUNT(*) FROM (" + cmdText + ") as T";
                    object obj = DBHelper.ExecuteScalar(countSQL);
                    if (obj != null && obj != DBNull.Value)
                    {
                        RecordCount = int.Parse(obj.ToString());
                    }
                    int CurrentPageIndex = pageIndex - 1;
                    int PageSizes = pageSize;
                    int rowStart = (CurrentPageIndex * PageSizes) + 1;//当前页的起始序号
                    int rowEnd = (CurrentPageIndex + 1) * PageSizes;//当前页的结束序号
                    string querySQL = @"declare @ID_Num int;
                                   SET @ID_Num = @ID_Num +1
                                   SELECT * FROM (SELECT t1.*,ROW_NUMBER() OVER (ORDER BY @ID_Num DESC)  sn 
                                   FROM (" + cmdText + ") t1) t2 " +
                                       " WHERE t2.sn BETWEEN " + rowStart.ToString() + " AND " + rowEnd.ToString();
                    return ExecuteReader(ConnectionStringLocalTransaction, CommandType.Text, querySQL, null);
                }
            }
            else
            {
                return ExecuteReader(ConnectionStringLocalTransaction, CommandType.Text, cmdText, null);
            }
        }


        /// <summary>
        /// 执行一条返回结果集的SqlCommand命令,带参数(分页)
        /// </summary>
        /// <param name="cmdText">T-SQL语句</param>
        /// <param name="pageIndex">页索引</param>
        /// <param name="pageSize">页数据大小</param>
        /// <param name="RecordCount">输出参数，输出总记录条数</param>
        /// <param name="commandParameters">sql参数</param>
        /// <returns>返回一个包含结果的SqlDataReader</returns>
        public static SqlDataReader ExecuteReader(string cmdText, int pageIndex, int pageSize, out int RecordCount, params SqlParameter[] commandParameters)
        {
            RecordCount = 0;
            if (!string.IsNullOrEmpty(cmdText))
            {
                if (cmdText.ToLower().IndexOf("order") > -1)
                {
                    string strCmdText1 = cmdText.Substring(0, cmdText.ToLower().IndexOf("order"));
                    string strCmdText2 = cmdText.Substring(cmdText.ToLower().IndexOf("order") + 1);
                    string countSQL = "SELECT COUNT(*) FROM (" + strCmdText1 + ") as T";
                    object obj = DBHelper.ExecuteScalar(countSQL, commandParameters);
                    if (obj != null && obj != DBNull.Value)
                    {
                        RecordCount = int.Parse(obj.ToString());
                    }
                    int CurrentPageIndex = pageIndex - 1;
                    int PageSizes = pageSize;
                    int rowStart = (CurrentPageIndex * PageSizes) + 1;//当前页的起始序号
                    int rowEnd = (CurrentPageIndex + 1) * PageSizes;//当前页的结束序号
                    string querySQL = @"declare @ID_Num int;
                                   SET @ID_Num = @ID_Num +1
                                   SELECT * FROM (SELECT t1.*,ROW_NUMBER() OVER (ORDER BY @ID_Num DESC)  sn 
                                   FROM (" + strCmdText1 + ") t1) t2 " +
                                       " WHERE t2.sn BETWEEN " + rowStart.ToString() + " AND " + rowEnd.ToString() + strCmdText2;
                    if (commandParameters != null)
                    {
                        return ExecuteReader(ConnectionStringLocalTransaction, CommandType.Text, querySQL, commandParameters);
                    }
                    else
                    {
                        return ExecuteReader(ConnectionStringLocalTransaction, CommandType.Text, querySQL, null);
                    }

                }
                else
                {
                    string countSQL = "SELECT COUNT(*) FROM (" + cmdText + ") as T";
                    object obj = DBHelper.ExecuteScalar(countSQL, commandParameters);
                    if (obj != null && obj != DBNull.Value)
                    {
                        RecordCount = int.Parse(obj.ToString());
                    }
                    int CurrentPageIndex = pageIndex - 1;
                    int PageSizes = pageSize;
                    int rowStart = (CurrentPageIndex * PageSizes) + 1;//当前页的起始序号
                    int rowEnd = (CurrentPageIndex + 1) * PageSizes;//当前页的结束序号
                    string querySQL = @"declare @ID_Num int;
                                   SET @ID_Num = @ID_Num +1
                                   SELECT * FROM (SELECT t1.*,ROW_NUMBER() OVER (ORDER BY @ID_Num DESC)  sn 
                                   FROM (" + cmdText + ") t1) t2 " +
                                       " WHERE t2.sn BETWEEN " + rowStart.ToString() + " AND " + rowEnd.ToString();
                    if (commandParameters != null)
                    {
                        return ExecuteReader(ConnectionStringLocalTransaction, CommandType.Text, querySQL, commandParameters);
                    }
                    else
                    {
                        return ExecuteReader(ConnectionStringLocalTransaction, CommandType.Text, querySQL, null);
                    }
                }

            }
            else
            {
                return ExecuteReader(ConnectionStringLocalTransaction, CommandType.Text, cmdText, null);
            }

        }
        #endregion


        #region ExecuteScalar
        /// <summary>
        /// 执行一条返回第一条记录第一列的SqlCommand命令，通过专用的连接字符串。 
        /// 使用参数数组提供参数
        /// </summary>
        /// <remarks>
        /// 使用示例：  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">一个有效的数据库连接字符串</param>
        /// <param name="commandType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个object类型的数据，可以通过 Convert.To{Type}方法转换类型</returns>
        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
                object obj = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return obj;
            }
        }
        /// <summary>
        /// 执行一条返回第一条记录第一列的SqlCommand命令，默认使用SQL语句
        /// </summary>
        /// <param name="cmdText">T-SQL语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个object类型的数据，可以通过 Convert.To{Type}方法转换类型</returns>
        public static object ExecuteScalar(string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecuteScalar(ConnectionStringLocalTransaction, CommandType.Text, cmdText, commandParameters);
        }
        /// <summary>
        /// 执行一条返回第一条记录第一列的SqlCommand命令,不使用参数
        /// </summary>
        /// <param name="cmdText">T-SQL语句</param>
        /// <returns>返回一个object类型的数据，可以通过 Convert.To{Type}方法转换类型</returns>
        public static object ExecuteScalar(string cmdText)
        {
            return ExecuteScalar(ConnectionStringLocalTransaction, CommandType.Text, cmdText, null);
        }
        /// <summary>
        /// 执行一条返回第一条记录第一列的SqlCommand命令，通过已经存在的数据库连接。
        /// 使用参数数组提供参数
        /// </summary>
        /// <remarks>
        /// 使用示例： 
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">一个已经存在的数据库连接</param>
        /// <param name="commandType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个object类型的数据，可以通过 Convert.To{Type}方法转换类型</returns>
        public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {

            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            object obj = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return obj;
        }
        #endregion


        #region ExecuteDataSet(执行查询语句，返回DataSet)

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet ExecuteDataSet(string connectionString, string SQLString)
        {
            if (SQLString != null && SQLString.Trim() != "")
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        connection.Open();
                        SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                        command.Fill(ds, "ds");
                    }
                    catch (System.Data.SqlClient.SqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
            else
            {
                return null;
            }
        }


        public static DataSet ExecuteDataSet(string connectionString, string SQLString, params SqlParameter[] Parameter)
        {
            if (SQLString != null && SQLString.Trim() != "")
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        connection.Open();
                        SqlDataAdapter adp = new SqlDataAdapter(SQLString, connection);
                        SqlCommand command = connection.CreateCommand();
                        command.CommandText = SQLString;
                        if (Parameter.Length > 0)
                        {
                            foreach (SqlParameter parm in Parameter)
                                command.Parameters.Add(parm);
                        }
                        adp.SelectCommand = command;
                        adp.Fill(ds, "ds");
                    }
                    catch (System.Data.SqlClient.SqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 执行查询语句，返回DataSet，省略查询字符串
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet ExecuteDataSet(string SQLString)
        {
            return ExecuteDataSet(ConnectionStringLocalTransaction, SQLString);
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString"></param>
        /// <param name="Parameter"></param>
        /// <returns></returns>
        public static DataSet ExecuteDataSet(string SQLString, params SqlParameter[] Parameter)
        {
            return ExecuteDataSet(ConnectionStringLocalTransaction, SQLString, Parameter);
        }

        #endregion


        #region 缓存参数数组
        /// <summary>
        /// 缓存参数数组
        /// </summary>
        /// <param name="cacheKey">参数缓存的键值</param>
        /// <param name="cmdParms">被缓存的参数列表</param>
        public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
        {
            parmCache[cacheKey] = commandParameters;
        }

        /// <summary>
        /// 获取被缓存的参数
        /// </summary>
        /// <param name="cacheKey">用于查找参数的KEY值</param>
        /// <returns>返回缓存的参数数组</returns>
        public static SqlParameter[] GetCachedParameters(string cacheKey)
        {
            SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];

            if (cachedParms == null)
                return null;

            //新建一个参数的克隆列表
            SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];

            //通过循环为克隆参数列表赋值
            for (int i = 0, j = cachedParms.Length; i < j; i++)
                //使用clone方法复制参数列表中的参数
                clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();

            return clonedParms;
        }
        #endregion


        #region 为执行命令准备参数
        /// <summary>
        /// 为执行命令准备参数
        /// </summary>
        /// <param name="cmd">SqlCommand 命令</param>
        /// <param name="conn">已经存在的数据库连接</param>
        /// <param name="trans">数据库事物处理</param>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="cmdText">Command text，T-SQL语句 例如 Select * from Products</param>
        /// <param name="cmdParms">返回带参数的命令</param>
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {

            //判断数据库连接状态
            if (conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;

            //判断是否需要事物处理
            if (trans != null)
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;

            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }
        #endregion

    }
}
